﻿#include "Parser.h"
#include "Num_Node.h"
#include "Plus_Node.h"
#include "Minus_Node.h" 
#include "Mul_Node.h"
#include "Div_Node.h"
#include "Posi_Sign_Node.h"
#include "Nega_Sign_Node.h"
Base_Node* Parser::parse_expr(const char* str)
{
	exprText = str;
	theLexer = new Lexer(str); //这个对象需要在Parser的析构函数中delete掉
	Lexer::Token_type tok = theLexer->get_token();
	if (tok == Lexer::PRINT || tok == Lexer::END) return NULL;  // 空表达式
	Base_Node* root = expr(false);
	return root;
}


Base_Node* Parser::expr(bool get)
{
	Base_Node* left = term(get);
	Base_Node* right;

	for (;;) {
		switch (theLexer->currentToken()) {
		case Lexer::PLUS:
			right = term(true);
			left = new Plus_Node(left, right);
			break;
		case Lexer::MINUS:
			right = term(true);
			left = new Minus_Node(left, right);
			break;
		default:
			return left;
		}
	}
}

Base_Node* Parser::term(bool get)
{
	Base_Node* left = prim(get);
	Base_Node* right;
	for (; ;) {
		switch (theLexer->currentToken()) {
		case Lexer::MUL:
			right = prim(true);
			left = new Mul_Node(left, right);
			break;
		case Lexer::DIV:
			right = prim(true);
			left = new Div_Node(left, right);
			break;
		default:
			return left;
		}
	}
}

Base_Node* Parser::prim(bool get)
{
	if (get)
		theLexer->get_token();
	switch (theLexer->currentToken()) {
	case Lexer::NUMBER:
		theLexer->get_token();
		return new Num_Node(theLexer->value());
	case Lexer::LP:
	{Base_Node* p = expr(true);
	if (theLexer->currentToken() != Lexer::RP)
		throw Bad_Expr();
	theLexer->get_token();
	return p; }
	default:
		Error::error("Error");
	}
}
